/**
 * author:Administrator
 * date:2016/2/23
 * desc:  广义上的商品，包括 商品(狭义) 服务
 */

'use strict';
let Repo = require('./WareRepo.js');
let WareSnapshot = require('./WareSnapshot.js');
let FormatDate = require('../../../infrastructure/appUtil/FormatDate.js');
let DomainModel = require('../../../lib/DomainModel.js');
let events = require('../../saga/domainEvent.js');

let _BASE_VER = 1;
let STATUS_ENUM = {
  ok: 'ok', //
  na: 'na', // not available
};

let WARE_CONST = {
  unlimit_count: -1,
};

class Ware extends DomainModel {
  constructor() {
    super();
  }

  static freshNew(pojo) {
    let ware = new Ware();
    ware.vendorId = pojo.vendorId;
    ware.categoryId = pojo.categoryId;
    ware.name = pojo.name;
    ware.price = pojo.price;
    ware.maxCount = pojo.maxCount;
    ware.imgUrls = pojo.imgUrls;
    ware.desc = pojo.desc;

    //
    ware.remain = pojo.maxCount;
    ware.ver = _BASE_VER;
    ware.createdAt = FormatDate.unixTimestamp();
    ware.updatedAt = FormatDate.unixTimestamp();
    return ware;
  }

  /**
   * 从数据库中读取，re-constructor an obj
   * @param pojo
   */
  static rebuild(pojo) {
    let ware = new Ware();
    let keys = Object.keys(pojo);
    for (let key of keys) {
      ware[key] = pojo[key];
    }
    return ware;
  }

  * store() {
    yield Repo.store(this);
  }

  /**
   * 创建快照
   * 商品在创建、升级时，需要创建快照
   */
  * createSnapshot() {
    let snapshot = WareSnapshot.fromWare(this);
    yield snapshot.store();
    return snapshot;
  }

  /**
   * 为订单预留一定数量的 ware
   * @param order
   * @return true,false
   */
  * reserve(order, sagaId) {
    let isOk = yield Repo.decrease(this.id, order.wareCount);
    if (isOk) {
      this.pubDomainEvent(new events.WareReserved(sagaId, order));
    } else {
      this.pubDomainEvent(new events.WareLacking(sagaId, order));
    }
  }

  /**
   * 升级属性
   */
  * updateWare(json) {
    yield this.createSnapshot();

    let preVer = this.ver;
    let keys = Object.keys(json);
    for (var key of keys) {
      this[key] = json[key]
    }
    this.ver = preVer + 1;

    yield this.store();
    return true;
  }

  /**
   * 获取产品快照
   */
  * getSnapshot() {
    let snapShot = yield Repo.findSnapshotByWare({wareId: this.id, ver: this.ver});
    return snapShot;
  }

}
Ware.WARE_CONST = WARE_CONST;
module.exports = Ware;